#include "board.h"
#include <iostream>
#include <iomanip>

Board::Board() : grid(SIZE, std::vector<Piece>(SIZE, Piece::EMPTY)), currentPlayer(Piece::BLACK) {}

void Board::initialize() {
    for (int i = 0; i < SIZE; ++i) {
        for (int j = 0; j < SIZE; ++j) {
            grid[i][j] = Piece::EMPTY;
        }
    }
    currentPlayer = Piece::BLACK;
}

bool Board::isValidMove(int x, int y) const {
    return x >= 0 && x < SIZE && y >= 0 && y < SIZE && grid[x][y] == Piece::EMPTY;
}

bool Board::placePiece(int x, int y, Piece piece) {
    if (!isValidMove(x, y)) return false;
    grid[x][y] = piece;
    return true;
}

bool Board::checkWin(int x, int y) const {
    if (grid[x][y] == Piece::EMPTY) return false;
    
    Piece target = grid[x][y];
    int directions[4][2] = {{1,0}, {0,1}, {1,1}, {1,-1}};
    
    for (auto& dir : directions) {
        int count = 1;
        
        // 正向检查
        for (int i = 1; i <= 4; ++i) {
            int nx = x + dir[0] * i;
            int ny = y + dir[1] * i;
            if (nx < 0 || nx >= SIZE || ny < 0 || ny >= SIZE || grid[nx][ny] != target) break;
            count++;
        }
        
        // 反向检查
        for (int i = 1; i <= 4; ++i) {
            int nx = x - dir[0] * i;
            int ny = y - dir[1] * i;
            if (nx < 0 || nx >= SIZE || ny < 0 || ny >= SIZE || grid[nx][ny] != target) break;
            count++;
        }
        
        if (count >= 5) return true;
    }
    return false;
}

bool Board::isFull() const {
    for (int i = 0; i < SIZE; ++i) {
        for (int j = 0; j < SIZE; ++j) {
            if (grid[i][j] == Piece::EMPTY) return false;
        }
    }
    return true;
}

void Board::display() const {
    std::cout << "  ";
    for (int i = 0; i < SIZE; ++i) {
        std::cout << std::setw(2) << i << " ";
    }
    std::cout << "\n";
    
    for (int i = 0; i < SIZE; ++i) {
        std::cout << std::setw(2) << i << " ";
        for (int j = 0; j < SIZE; ++j) {
            char symbol = '.';
            if (grid[i][j] == Piece::BLACK) symbol = 'X';
            else if (grid[i][j] == Piece::WHITE) symbol = 'O';
            std::cout << symbol << "  ";
        }
        std::cout << "\n";
    }
    std::cout << "当前玩家: " << (currentPlayer == Piece::BLACK ? "X(黑)" : "O(白)") << "\n";
}

Piece Board::getCurrentPlayer() const { return currentPlayer; }

void Board::switchPlayer() {
    currentPlayer = (currentPlayer == Piece::BLACK) ? Piece::WHITE : Piece::BLACK;
}

int Board::getSize() const { return SIZE; }

Piece Board::getPiece(int x, int y) const { return grid[x][y]; }